﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using GifTools;
using System.Drawing.Imaging;
using Newtonsoft.Json;
using System.IO;

namespace BusinessClass
{
    public class MakeHelper
    {
        dynamic rules;
        string workingDir;
        string ttfPath;
        public MakeHelper()
        {

        }
        public IEnumerable<string> Run(dynamic rulejson, string ttfPath, string workingDir, float offsetx, float offsety)
        {
            rules = rulejson;
            string txtRenderingHint = rulejson.hint;
            this.workingDir = workingDir;
            this.ttfPath = ttfPath;
            List<string> makedFiles = new List<string>();
            foreach (dynamic rule in rules.rules)
            {
                if (rule.type == "png")
                {
                    makedFiles = makedFiles.Concat((IEnumerable<string>)makePic(rule, txtRenderingHint, offsetx, offsety)).ToList();
                }
                else
                {
                    makedFiles.Add(makeTxt(rule));
                }
            }
            return makedFiles;
        }


        //{
        //    "name": "地图链接",
        //    "input": "",
        //    "sname": "dt.txt",
        //    "len": -1,
        //    "type": "txt",
        //    "format": "dtdz={0}"
        //}
        public string makeTxt(dynamic txtJson)
        {
            string outputFile;
            string name = txtJson.sname;
            string format = txtJson.format;
            string input = txtJson.input;
            outputFile = Common.conbindPath(workingDir, name);
            File.WriteAllText(outputFile,
                string.Format(format, input));
            return outputFile;
        }
        //        {
        //    "name": "地点",
        //    "input": "",
        //    "sname": "dd1;dd2",
        //    "len": 16,
        //    "type": "png",
        //    "width": "325",
        //    "height": "28",
        //    "fontsize": "15",
        //    "color": "#FFFF00",
        //    "backcolor": "#906d4f",
        //"oriOption": "V",
        //"posOption": "L"
        //}
        public IEnumerable<string> makePic(dynamic picJson, string txtRenderingHint, float offsetx, float offsety)
        {
            List<string> outputFiles = new List<string>();
            int width = Convert.ToInt32(picJson.width);
            int height = Convert.ToInt32(picJson.height);
            int fontSize = Convert.ToInt32(picJson.fontsize);
            bool bold = Convert.ToBoolean(picJson.bold);
            string color = picJson.color;
            Color pen = color.ToColor();
            string bc = picJson.backcolor;
            Color backGroundPen = bc.ToColor();
            #region 构造Font
            Font f;
            FontBuilder fb = new FontBuilder(ttfPath, fontSize, bold);
            f = fb.TheFont;
            #endregion
            int limitedLen = Convert.ToInt32(picJson.len);
            string input = picJson.input;
            string sname = picJson.sname;
            DrawStringHelper.OriOptions oriOp = DrawStringHelper.OriOptions.H;
            if (((string)picJson.oriOption).ToUpper() == "V")
                oriOp = DrawStringHelper.OriOptions.V;
            DrawStringHelper.Hor hor = DrawStringHelper.Hor.C;
            if (((string)picJson.hor).ToUpper() == "R")
            {
                hor = DrawStringHelper.Hor.R;
            }
            else if (((string)picJson.hor).ToUpper() == "L")
            {
                hor = DrawStringHelper.Hor.L;
            }
            DrawStringHelper.Ver ver = DrawStringHelper.Ver.C;
            if (((string)picJson.ver).ToUpper() == "T")
            {
                ver = DrawStringHelper.Ver.T;
            }
            else if (((string)picJson.ver).ToUpper() == "B")
            {
                ver = DrawStringHelper.Ver.B;
            }
            if (sname.IndexOf(";") > 0)
            {
                var names = sname.Split(';');
                int i = 0;
                while (input.Length > limitedLen)
                {
                    string t = input.Substring(0, limitedLen);
                    string outPutPath = Common.conbindPath(workingDir, names[i++]);
                    outputFiles.Add(make(oriOp, hor, ver, width, height, pen, backGroundPen, t, f, txtRenderingHint, outPutPath, offsetx, offsety));
                    input = input.Substring(limitedLen);
                }
                if (input.Length > 0)
                {
                    string outPutPath = Common.conbindPath(workingDir, names[i++]);
                    outputFiles.Add(make(oriOp, hor, ver, width, height, pen, backGroundPen, input, f, txtRenderingHint, outPutPath, offsetx, offsety));
                }
                while (i < names.Length)
                {
                    string outPutPath = Common.conbindPath(workingDir, names[i++]);
                    outputFiles.Add(make(oriOp, hor, ver, width, height, pen, backGroundPen, " ", f, txtRenderingHint, outPutPath, offsetx, offsety));

                }
            }
            else
            {
                string outPutPath = Common.conbindPath(workingDir, sname);
                outputFiles.Add(make(oriOp, hor, ver, width, height, pen, backGroundPen, input, f, txtRenderingHint, outPutPath, offsetx, offsety));
            }
            return outputFiles;
        }

        private string make(DrawStringHelper.OriOptions oriOp, DrawStringHelper.Hor hor, DrawStringHelper.Ver ver, int width, int height, Color pen, Color backGroundPen, string text, Font f, string txtRenderingHint, string outPutPath, float offsetx, float offsety)
        {
            Bitmap canvas = new Bitmap(width, height);
            Brush penBrush = new SolidBrush(pen);
            using (Graphics g = Graphics.FromImage(canvas))
            {
                //g.Clear(backGroundPen);
                //g.Save();
                g.FillRectangle(new SolidBrush(backGroundPen), 0, 0, width, height);
                g.Save();
            }
            canvas = DrawStringHelper.drawNew(text, canvas, f, penBrush, backGroundPen, oriOp, hor, ver, txtRenderingHint);
            canvas.MakeTransparent(backGroundPen);
            canvas.Save(outPutPath, ImageFormat.Png);
            return outPutPath;
        }


        #region 旧代码
        ///// <summary>
        ///// 根据模板中的定义，以及传入的值，生成一系列的图片。
        ///// 参数是 生成图片需要的文字  Name为key  eg  boyname  value 江先生
        ///// </summary>
        ///// <param name="values"></param>
        //public void MakeImages(Dictionary<string, string> data, string saveDir)
        //{
        //    //是文字，而且又有传入的，就生成
        //    var drawImages = processor.mImages.mImage.Where(
        //        img => img.mIsDraw.ToLower() == "true" && data.ContainsKey(img.mName));
        //    foreach (var imgProcessor in drawImages)
        //    {
        //        int width = Convert.ToInt32(imgProcessor.mWidth);
        //        int height = Convert.ToInt32(imgProcessor.mHeigth);
        //        int fontSize = Convert.ToInt32(imgProcessor.mFontSize);
        //        Color pen = imgProcessor.mColor.ToColor();
        //        Color backGroundPen = imgProcessor.mBackColor.ToColor();
        //        string text = data[imgProcessor.mName];
        //        FontStyle fs = imgProcessor.mIsBold.ToLower() == "true" ? FontStyle.Bold : FontStyle.Regular;
        //        string outPutPath = Common.conbindPath(saveDir, imgProcessor.mSaveName);
        //        make(width, height, fontSize, pen, backGroundPen, text, fs, outPutPath);
        //    }
        //}
        ///// <summary>
        ///// 添加偏移左上角功能
        ///// </summary>
        ///// <param name="data"></param>
        ///// <param name="saveDir"></param>
        ///// <param name="offsetx"></param>
        ///// <param name="offsety"></param>
        //public void MakeImages(Dictionary<string, string> data, string saveDir, float offsetx, float offsety)
        //{
        //    //是文字，而且又有传入的，就生成
        //    var drawImages = processor.mImages.mImage.Where(
        //        img => img.mIsDraw.ToLower() == "true" && data.ContainsKey(img.mName));
        //    foreach (var imgProcessor in drawImages)
        //    {
        //        int width = Convert.ToInt32(imgProcessor.mWidth);
        //        int height = Convert.ToInt32(imgProcessor.mHeigth);
        //        int fontSize = Convert.ToInt32(imgProcessor.mFontSize);
        //        Color pen = imgProcessor.mColor.ToColor();
        //        Color backGroundPen = imgProcessor.mBackColor.ToColor();
        //        string text = data[imgProcessor.mName];
        //        FontStyle fs = imgProcessor.mIsBold.ToLower() == "true" ? FontStyle.Bold : FontStyle.Regular;
        //        string outPutPath = Common.conbindPath(saveDir, imgProcessor.mSaveName);
        //        make(width, height, fontSize, pen, backGroundPen, text, fs, outPutPath, offsetx, offsety);
        //    }
        //}

        #endregion

        //private void make(int width, int height, int fontSize, Color pen, Color backGroundPen, string text, FontStyle fs, string outPutPath)
        //{
        //    Bitmap bitmap = new Bitmap(width, height);
        //    Graphics g = Graphics.FromImage(bitmap);
        //    Brush penBrush = new SolidBrush(pen);
        //    g.Clear(backGroundPen);

        //    Font f = new Font(
        //           pfc.Families[0],
        //           fontSize,
        //           fs
        //        );
        //    //设置文本输出质量
        //    g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;
        //    g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
        //    g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
        //    g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;


        //    g.DrawString(text, f, penBrush, 0, 0);

        //    g.Save();
        //    g.Dispose();
        //    bitmap.MakeTransparent(backGroundPen);
        //    bitmap.Save(outPutPath, ImageFormat.Png);
        //}
        //public void MakeImage()
        //{

        //}
    }
}
